package com.panopset.centralen.resource;

import java.awt.Graphics;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.PixelGrabber;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.ImageIcon;

/**
 * Image Java package resource.
 *
 * @author Karl Dinwiddie
 */
public final class ImageResource {

    /**
     * 16x16 pixel image.
     */
    private Image image;

    /**
     * 16x16 pixes favicon buffered image.
     */
    private BufferedImage bufferedImage;

    /**
     * Path to the image.
     */
    private final String path;

    /**
     * Get java.awt.Image.
     *
     * @return favicon.
     */
    public Image getImage() {
        if (image == null) {
            image = new ImageIcon(Accessor.getPackageURL(path)).getImage();
        }
        return image;
    }

    /**
     * ImageAccessor constructor.
     *
     * @param newPath
     *            Path to image resource.
     */
    public ImageResource(final String newPath) {
        this.path = newPath;
    }

    /**
     * Get buffered image.
     *
     * @return BufferedImage.
     */
    public BufferedImage getBufferedImage() {
        if (bufferedImage == null) {
            bufferedImage = toBufferedImage(getImage());
        }
        return bufferedImage;
    }

    /**
     * Returns a buffered image with the contents of an image. Reference <a
     * href=" http://www.exampledepot.com/egs/java.awt.image/Image2Buf.html ">
     * http://www.exampledepot.com/egs/java.awt.image/Image2Buf.html </a>.
     *
     * @param sourceImage Source Image.
     * @return BufferedImage.
     */
    public static BufferedImage toBufferedImage(final Image sourceImage) {
        if (sourceImage instanceof BufferedImage) {
            return (BufferedImage) sourceImage;
        }

        // This code ensures that all the pixels in the image are loaded
        Image img = new ImageIcon(sourceImage).getImage();

        // Determine if the image has transparent pixels; for this method's
        // implementation, see e661 Determining If an Image Has Transparent
        // Pixels
        boolean hasAlpha = hasAlpha(img);

        // Create a buffered image with a format that's compatible with the
        // screen
        BufferedImage bimage = null;
        GraphicsEnvironment ge = GraphicsEnvironment
                .getLocalGraphicsEnvironment();
        try {
            // Determine the type of transparency of the new buffered image
            int transparency = Transparency.OPAQUE;
            if (hasAlpha) {
                transparency = Transparency.BITMASK;
            }

            // Create the buffered image
            GraphicsDevice gs = ge.getDefaultScreenDevice();
            GraphicsConfiguration gc = gs.getDefaultConfiguration();
            bimage = gc.createCompatibleImage(img.getWidth(null), img
                    .getHeight(null), transparency);
        } catch (HeadlessException e) {
            Logger.getAnonymousLogger().log(Level.WARNING, e.getMessage());
        }

        if (bimage == null) {
            // Create a buffered image using the default color model
            int type = BufferedImage.TYPE_INT_RGB;
            if (hasAlpha) {
                type = BufferedImage.TYPE_INT_ARGB;
            }
            bimage = new BufferedImage(img.getWidth(null), img
                    .getHeight(null), type);
        }

        // Copy image to buffered image
        Graphics g = bimage.createGraphics();

        // Paint the image onto the buffered image
        g.drawImage(img, 0, 0, null);
        g.dispose();

        return bimage;
    }

    /**
     * Returns true if the specified image has transparent pixels.
     *
     * Reference <a href=
     * "http://www.exampledepot.com/egs/java.awt.image/HasAlpha.html"
     * >http://www.exampledepot.com/egs/java.awt.image/HasAlpha.html</a>.
     *
     * @param image Image to check.
     * @return true if image has transparent pixels.
     */
    public static boolean hasAlpha(final Image image) {
        // If buffered image, the color model is readily available
        if (image instanceof BufferedImage) {
            BufferedImage bimage = (BufferedImage) image;
            return bimage.getColorModel().hasAlpha();
        }

        // Use a pixel grabber to retrieve the image's color model;
        // grabbing a single pixel is usually sufficient
        PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
        try {
            pg.grabPixels();
        } catch (InterruptedException e) {
            Logger.getLogger(ImageResource.class.getName()).log(Level.FINEST,
                    e.getMessage(), e);
        }

        // Get the image's color model
        ColorModel cm = pg.getColorModel();
        return cm.hasAlpha();
    }
}
